// Display saved aliases on page load
function displaySavedAliases() {
  const savedAliasesTable = document.getElementById('saved-aliases-table');

  chrome.storage.local.get('tabList', (result) => {
    const tabNameMap = result.tabList || {};
    const tableBody = document.querySelector("#saved-aliases-table tbody");
    // 将数据填充到表中
    function populateTable() {
      tableBody.innerHTML = "";
      let index = 0;
      let delButtonLabel = chrome.i18n.getMessage('delButton');
      for (const url in tabNameMap) {
        index++;
        const row = document.createElement("tr");

        row.innerHTML = `
                    <td>${index}</td>
                    <td>${tabNameMap[url]}</td>
                    <td><a href="${url}" target="_blank">${url}</a></td>
                    <td><button class="delete-btn" data-url="${url}">${delButtonLabel}</button></td>
                `;
        tableBody.appendChild(row);
      }
    }

    populateTable();

    // 添加删除按钮的点击事件
    tableBody.addEventListener("click", function (event) {
      if (event.target.classList.contains("delete-btn")) {
        const url = event.target.getAttribute("data-url");
        delete tabNameMap[url];
        chrome.storage.local.set({ tabList: tabNameMap }, () => {
          displaySavedAliases(tabNameMap); // Re-display the updated list
        });
      }
    });
  });
}

// Call the function to display saved aliases on page load
displaySavedAliases();

// Event listener for form submission to add/update alias
document.getElementById('aliasForm').addEventListener('submit', (event) => {
  /**
   * 阻止事件的默认行为。
   * 该方法用于取消浏览器的默认行为，比如阻止链接的跳转、表单的提交等。
   * 该方法本身没有参数和返回值。
   */
  event.preventDefault();

  const url = normalizeUrl(document.getElementById('url').value);
  const alias = document.getElementById('alias').value;

  chrome.storage.local.get('tabList', (result) => {
    const tabNameMap = result.tabList || {};

    // Update the alias for the given URL
    tabNameMap[url] = alias;

    chrome.storage.local.set({ tabList: tabNameMap }, () => {
      // Re-display the saved aliases after updating
      displaySavedAliases(tabNameMap);
    });
  });

  // Clear the form fields after submission
  document.getElementById('url').value = '';
  document.getElementById('alias').value = '';
});

// 规范化URL函数
function normalizeUrl(url) {
  return new URL(url).href;
}

// Event listener for export button click
document.getElementById('export-btn').addEventListener('click', () => {
  chrome.storage.local.get('tabList', (result) => {
    const tabNameMap = result.tabList || {};
    let exportData = '\uFEFFCustom Name,URL\n'; // Add BOM and CSV header

    // Format data as CSV
    for (const url in tabNameMap) {
      exportData += `${tabNameMap[url]},${url}\n`;
    }

    // Create a Blob object representing the data as a CSV file
    const blob = new Blob([exportData], { type: 'text/csv;charset=utf-8;' });

    // Create a download link and trigger the download
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'tab_aliases.csv';
    a.click();

    // Clean up the URL object
    URL.revokeObjectURL(url);
  });
});

// Event listener for import button click
document.getElementById('import-btn').addEventListener('click', () => {
  // Create an input element for file selection
  const input = document.createElement('input');
  input.type = 'file';
  input.accept = '.csv';

  // Listen for file selection
  input.addEventListener('change', (event) => {
    const file = event.target.files[0];
    if (!file) {
      return;
    }

    // Read the file content
    const reader = new FileReader();
    reader.onload = (e) => {
      const csvData = e.target.result;
      const newTabNameMap = parseCSV(csvData);

      chrome.storage.local.get('tabList', (result) => {
        const currentTabNameMap = result.tabList || {};
        const mergedTabNameMap = { ...newTabNameMap, ...currentTabNameMap };
        chrome.storage.local.set({ tabList: mergedTabNameMap }, () => {
          // Re-display the saved aliases after updating
          displaySavedAliases();
        });
      });
    };

    reader.readAsText(file);
  });

  input.click();
});

// Function to parse CSV data
function parseCSV(csvData) {
  const tabNameMap = {};
  const lines = csvData.split('\n');
  for (let i = 1; i < lines.length; i++) { // Skip the header line
    const line = lines[i].trim();
    if (line) {
      const [alias, url] = line.split(',');
      tabNameMap[url] = alias;
    }
  }
  return tabNameMap;
}

document.getElementById('export-btn').textContent = chrome.i18n.getMessage('exportButton');
document.getElementById('import-btn').textContent = chrome.i18n.getMessage('importButton');
